﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.IO;
using System.Collections;
using Consultant.Models;

namespace Consultant.Controllers
{
    [HandleError]
    public class ServerController : Controller
    {
        public string path_prefix = @"C:\\project\\";
        private DataManager _dataManager;

        public ServerController(DataManager dataManager)
            : this(dataManager,null, null)
        {
        }

        public ServerController(DataManager dataManager,IFormsAuthentication formsAuth, IMembershipService service)
        {
            _dataManager = dataManager;
            FormsAuth = formsAuth ?? new FormsAuthenticationService();
            MembershipService = service ?? new AccountMembershipService();
        }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }
        public ActionResult Index()
        {
            //XDocument doc1 = XDocument.Load("buffer.xml");

            return View();
        }
        public class rData
        {
            public string message;
            public int id;
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult SendMessC(string mess)
        {
            string id = Session.SessionID;
            string time = DateTime.Now.ToLongTimeString();
            //string id = (string)Session["id"];
            string filename = path_prefix + id + ".xml";
            XDocument doc;
            FileInfo f = new FileInfo(filename);
            if (f.Exists)
            {
                doc = XDocument.Load(filename);                
            }
            else
            {
                doc = new XDocument(new XElement("root",
                    //new XElement("op_id", ""),
                 new XElement("op_buff", ""),
                 new XElement("client_buff", ""),
                 new XElement("op_timeout", ""),
                 new XElement("client_timeout", "")
                 ));
                string p = path_prefix + "call.xml";
                XDocument call = XDocument.Load(p);
                XElement client = new XElement("client", new XAttribute("id", id));
                client.Add(new XElement("operator", "Вася"));
                call.Root.Add(client);
                call.Save(p);
            }            
            string temp = id + "[" + time + "]:" + mess + "<br>";
            doc.Root.Element("client_buff").Value += temp;
            
            doc.Save(filename);
            temp = "Вы[" + time + "]" + mess;
            rData postback = new rData { message = temp, id = 0 };
            return Json(postback, JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetMessC()
        {
            //string filename = Session.SessionID + ".xml";
            string filename = path_prefix + Session.SessionID + ".xml";
            FileInfo f = new FileInfo(filename);
            if (f.Exists)
            {
                XDocument doc = XDocument.Load(filename);
                string op_timeout = doc.Root.Element("op_timeout").Value;
                string temp = "";
                DateTime timeOut = DateTime.Now.AddSeconds(45);
                doc.Root.Element("client_timeout").Value = timeOut.ToLongTimeString();
                if (op_timeout != "")
                {
                    if (DateTime.Parse(op_timeout) > DateTime.Now.ToLocalTime())
                    {
                        temp = doc.Root.Element("op_buff").Value;
                        doc.Root.Element("op_buff").Value = "";
                        
                        doc.Save(filename);
                    }
                    else
                    {
                        if ((bool)Session["bOpState"])
                        {
                            temp = "Клиент закрыл чат!!!";
                        }
                        else temp = "";
                        f.Delete();
                    }
                }
                
                
                doc.Save(filename);
                rData postback = new rData { message = temp, id = 0 };
                return Json(postback, JsonRequestBehavior.AllowGet);
            }
            else
            {
                if ((bool)Session["bOpState"])
                {
                    Session["bOpState"] = false;
                    return Json(new { message = "Оператор закрыл чат!!!" }, JsonRequestBehavior.AllowGet);                    
                }
                else return Json(new { message = "" }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult SendMessOp(string mess, string id)
        {

            string filename = path_prefix + id + ".xml";
            FileInfo f = new FileInfo(filename);
            if (f.Exists)
            {
                XDocument doc = XDocument.Load(filename);
                string time = DateTime.Now.ToLongTimeString();
                string temp = Session["name"] + "[" + time + "]:" + mess + "<br>";
                doc.Root.Element("op_buff").Value += temp;
                doc.Save(filename);
                temp = "Вы[" + time + "]" + mess;
                rData postback = new rData { message = temp, id = 0 };
                return Json(postback, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { message = "" }, JsonRequestBehavior.AllowGet); 
            }
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetMessOp(string id)
        {
            string filename = path_prefix + id + ".xml";
            DateTime time = DateTime.Now.ToLocalTime();
            FileInfo f = new FileInfo(filename);
            if (f.Exists)
            {
                XDocument doc = XDocument.Load(filename);
                string client_timeout = doc.Root.Element("client_timeout").Value;
                string temp = "";
                //DateTime a = DateTime.Now.ToLocalTime();
                DateTime timeOut = DateTime.Now.AddSeconds(45);
                doc.Root.Element("op_timeout").Value = timeOut.ToLongTimeString();
                if (client_timeout != "")
                {
                    if (DateTime.Parse(client_timeout) > DateTime.Now.ToLocalTime())
                    {
                        temp = doc.Root.Element("client_buff").Value;
                        doc.Root.Element("client_buff").Value = "";
                        
                        doc.Save(filename);
                    }
                    else
                    {
                        if ((bool)Session["bClientState"])
                        {
                        temp = "Клиент закрыл чат!!!";
                        }
                        else temp = "";
                        f.Delete();
                    }
                }
                rData postback = new rData { message = temp, id = 0 };
                return Json(postback, JsonRequestBehavior.AllowGet);
            }
                
            else 
            {
                if ((bool)Session["bClientState"])
                {
                    Session["bClientState"] = false;
                    return Json(new { message = "Клиент закрыл чат!!!" }, JsonRequestBehavior.AllowGet);
                }
                else return Json(new { message = "" }, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult Client()
        {
            /*string filename = Session.SessionID + ".xml";
            XDocument doc = new XDocument(new XElement("root",
                new XElement("op_id"),
                new XElement("op_buff"),
                new XElement("client_buff")
                ));
            doc.Save(filename);*/
            //Session["id"] = Session.SessionID;
            if (!_dataManager.Operator.IsAnybodyHome())
            {
                ViewData["message"] = "На данный момент ни одного консультанта онлайн!!!";
            }
            else { ViewData["message"] = ""; }
            Session["bOpState"] = true;
            return View();
        }
        [Authorize]
        public ActionResult Operator()
        {
            Session["name"] = User.Identity.Name;
            Session["bClientState"] = true;
            ViewData["title"] = Session["name"].ToString();
            return View();
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Operator_chat(string id)
        {
            ViewData["c_id"] = id;
            return View();
        }
        public class GCall
        {
            public string id;
            public string mess;
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetCall()
        {
            string filename = path_prefix + "call.xml";
            List<GCall> res = new List<GCall>();
            //GCall client = new GCall();
            XDocument doc = XDocument.Load(filename);
            foreach (XElement c in doc.Root.Elements("client"))
            {
                string sid = c.Attribute("id").Value;
                string fn = path_prefix+sid+".xml";
                bool is_my_client = false;
                XDocument m_ge = XDocument.Load(fn);
                GCall client = new GCall();
                client.mess = m_ge.Root.Element("client_buff").Value;
                client.id = sid;
                foreach (XElement op in c.Elements("operator"))
                {
                    string name = Session["name"].ToString(); 
                    if (op.Value == name)
                    {
                        is_my_client = true;
                    }
                }
                if (is_my_client)
                {
                    res.Add(client);
                }
            }
            return Json(res, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Accept(string id)
        {
            string filename = path_prefix + "call.xml";
            XDocument doc = XDocument.Load(filename);
            IEnumerable<XElement> cl = doc.Root.Descendants("client").Where(c => c.Attribute("id").Value == id);
            cl.Remove();
            doc.Save(filename);
            return Json(new { res = true, c_id = id }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Reject(string id)
        {
            string filename = path_prefix + "call.xml";
            XDocument doc = XDocument.Load(filename);
            IEnumerable<XElement> cl = doc.Root.Descendants("client").Where(c => c.Attribute("id").Value == id);
            foreach (XElement el in cl)
            {
                foreach (XElement op in el.Elements("operator"))
                {
                    if (op.Value == Session["name"].ToString())
                    {
                        op.Remove();
                    }
                }
            }
            
            doc.Save(filename);
            return Json("", JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult ClientDisconnect()
        {
            string chatfilename = path_prefix + Session.SessionID + ".xml";
            FileInfo cfile = new FileInfo(chatfilename);
            if (cfile.Exists)
            {
                cfile.Delete();
            }
            string callfilename = path_prefix + "call.xml";
            FileInfo callfile = new FileInfo(callfilename);
            if (callfile.Exists)
            {
                XDocument doc = XDocument.Load(callfilename);
                IEnumerable<XElement> cl = doc.Root.Descendants("client").Where(c => c.Attribute("id").Value == Session.SessionID);
                cl.Remove();
                doc.Save(callfilename);
            }
            return Json(new { dis = true }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult OperatorDisconnect(string id)
        {
            string filename = path_prefix + id + ".xml";
            FileInfo file = new FileInfo(filename);
            if (file.Exists)
            {
                file.Delete();
            }
            return Json(new { dis = true }, JsonRequestBehavior.AllowGet);
        }
    }
}
